import axios from "axios";
import store from "../store";
import { getToken } from "@/utils/auth";
import { Message, MessageBox, Loading } from "element-ui";
import router from "../router";

// NOTE(Haobo): Create the axios root example.
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 30 * 1000
});

let loadingInstance;
// Sign in the request interceptors.
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["qb_token"] = getToken();
    }
    loadingInstance = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.4)'});
    return config
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// Sign in the response interceptors.
service.interceptors.response.use(
  response => {
    // 1 is success code
    const res = response.data;
    loadingInstance.close();
    if (res.code !== 1) {
      Message({
        message: res.msg,
        type: "error",
        duration: 5 * 1000
      });
      if (res.code === -7) {
        router.push({ path: "/noAuth/index" });
      }
      // 50008: illegal token;
      // 50012: sign in on other device;
      // 50014: token expire;
      // But now is disabled;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014 || res.code === -3) {
        MessageBox.confirm(
          "你已被登出，可以取消继续留在该页面，或者重新登录",
          "确定登出",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          store.dispatch("FedLogOut").then(() => {
            // For renew vue-router.
            location.reload();
          });
        });
      }
      return Promise.reject(response);
    } else {
      return response.data;
    }
  },
  error => {
    console.log("err" + error); // for debug
    loadingInstance.close();
    Message({
      message: error.msg || "网络环境不好，请稍后重试",
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
